# device_b.py
import pika

RABBITMQ_CONFIG = {
    "host": "10.0.106.15",
    "port": 5672,
    "username": "root",
    "password": "avs123456.",
}

credentials = pika.PlainCredentials(
    RABBITMQ_CONFIG["username"], RABBITMQ_CONFIG["password"]
)
connection_params = pika.ConnectionParameters(
    host=RABBITMQ_CONFIG["host"], port=RABBITMQ_CONFIG["port"], credentials=credentials
)

connection = pika.BlockingConnection(connection_params)
channel = connection.channel()

# 队列名称
command_queue = "command"
response_queue = "response"

# 确保队列存在
channel.queue_declare(queue=command_queue, durable=True)
channel.queue_declare(queue=response_queue, durable=True)


# 接收 command 并响应
def on_command(ch, method, properties, body):
    msg = body.decode("utf-8")
    print(f"[B] Received command from A: {msg}")

    # 模拟处理
    reply = f"Command '{msg}' executed successfully."

    # 发送响应
    channel.basic_publish(
        exchange="",
        routing_key=response_queue,
        body=reply.encode("utf-8"),
        properties=pika.BasicProperties(delivery_mode=2),
    )
    print(f"[B] Sent response to A: {reply}")

    ch.basic_ack(delivery_tag=method.delivery_tag)


# 启动监听
channel.basic_consume(
    queue=command_queue, on_message_callback=on_command, auto_ack=False
)
print("[B] Waiting for commands from A...")
channel.start_consuming()
